import { useState, useRef, useEffect } from 'react';
import { Button, Input, message, Modal, Slider, Space, Card, Row, Col, Typography } from 'antd';
import { UploadOutlined, EyeOutlined, DownloadOutlined } from '@ant-design/icons';
import * as pdfjsLib from 'pdfjs-dist';
import "pdfjs-dist/build/pdf.worker.entry";
const { TextArea } = Input;
const { Title, Text } = Typography;

// 设置PDF.js worker
// pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.8.69/pdf.worker.min.js';
// pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@4.8.69/build/pdf.worker.min.js';

pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.js';
const PdfQRCodeEditor = () => {
  const [pdfFile, setPdfFile] = useState(null);
  const [pdfPages, setPdfPages] = useState([]);
  const [qrText, setQrText] = useState('');
  const [qrPositions, setQrPositions] = useState([]);
  const [currentPage, setCurrentPage] = useState(0);
  const [loading, setLoading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const canvasRefs = useRef([]);
  const [qrSize, setQrSize] = useState(100);
  const [isDragging, setIsDragging] = useState(false);
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
  const [hoverPos, setHoverPos] = useState(null);
  const renderTaskRef = useRef(null);

  // 选择PDF文件
  const handleSelectPdf = async () => {
    try {
      console.log('开始选择PDF文件...');
      const filePath = await window.api.selectPdfFile();
      console.log('选择的文件路径:', filePath);
      if (filePath) {
        setPdfFile(filePath);
        await loadPdfPages(filePath);
        message.success('PDF文件加载成功');
      }
    } catch (error) {
      console.error('选择PDF文件失败:', error);
      message.error('选择PDF文件失败: ' + error.message);
    }
  };

  // 加载PDF页面
  const loadPdfPages = async (filePath) => {
    try {
      setLoading(true);
      console.log('开始加载PDF文件:', filePath);
      
      // 通过主进程读取PDF文件
      const result = await window.api.readPdfFile(filePath);
      console.log('读取PDF结果:', result);
      if (!result.success) {
        throw new Error(result.error);
      }
      
      // 将Array转换为ArrayBuffer
      const arrayBuffer = new Uint8Array(result.data).buffer;
      console.log('ArrayBuffer大小:', arrayBuffer.byteLength);
      
      const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise;
      console.log('PDF加载成功，页数:', pdf.numPages);
      
      const pages = [];
      for (let i = 1; i <= pdf.numPages; i++) {
        const page = await pdf.getPage(i);
        const viewport = page.getViewport({ scale: 1.0 });
        pages.push({ page, viewport, pageNumber: i });
        console.log(`第${i}页加载完成，尺寸:`, viewport.width, 'x', viewport.height);
      }
      
      console.log('所有页面加载完成，页面数量:', pages.length);
      setPdfPages(pages);
      setQrPositions([]);
      setCurrentPage(0);
    } catch (error) {
      console.error('加载PDF失败:', error);
      message.error('加载PDF失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 渲染PDF页面到Canvas
  const renderPage = async (page, viewport, canvas, pageIndex) => {
    if (renderTaskRef.current) {
      renderTaskRef.current.cancel();
      renderTaskRef.current = null;
    }
    const context = canvas.getContext('2d');
    canvas.width = viewport.width;
    canvas.height = viewport.height;

    const renderContext = {
      canvasContext: context,
      viewport: viewport
    };

    const renderTask = page.render(renderContext);
    renderTaskRef.current = renderTask;
    try {
      await renderTask.promise;
    } catch (e) {
      return;
    }
    renderTaskRef.current = null;

    // 绘制所有已标注二维码位置（灰色半透明方框和灰色边框）
    qrPositions
      .filter(pos => pos.pageIndex === pageIndex)
      .forEach(savedPosition => {
        context.save();
        context.globalAlpha = 0.3;
        context.fillStyle = '#888'; // 灰色
        context.fillRect(
          savedPosition.x,
          savedPosition.y,
          savedPosition.width,
          savedPosition.height
        );
        context.globalAlpha = 1.0;
        context.strokeStyle = '#444';
        context.lineWidth = 2;
        context.setLineDash([]);
        context.strokeRect(
          savedPosition.x,
          savedPosition.y,
          savedPosition.width,
          savedPosition.height
        );
        context.restore();
      });

    // 绘制鼠标悬停的二维码预览框
    if (hoverPos && pageIndex === currentPage) {
      context.save();
      context.globalAlpha = 0.3;
      context.strokeStyle = '#ff9800';
      context.lineWidth = 2;
      context.setLineDash([2, 2]);
      context.strokeRect(
        hoverPos.x - qrSize / 2,
        hoverPos.y - qrSize / 2,
        qrSize,
        qrSize
      );
      context.restore();
    }
  };

  // 鼠标移动时，记录悬停位置
  const handleMouseMove = (e, pageIndex) => {
    const canvas = e.target;
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    const pdfX = x * scaleX;
    const pdfY = canvas.height - (y * scaleY);
    setHoverPos({ x: pdfX, y: pdfY });
    if (isDragging && dragStart.pageIndex === pageIndex) {
      const deltaX = x - dragStart.x;
      const deltaY = y - dragStart.y;
      const existingIndex = qrPositions.findIndex(pos => pos.pageIndex === pageIndex);
      if (existingIndex >= 0) {
        const updatedPositions = [...qrPositions];
        updatedPositions[existingIndex] = {
          ...updatedPositions[existingIndex],
          x: updatedPositions[existingIndex].x + deltaX * scaleX,
          y: updatedPositions[existingIndex].y - deltaY * scaleY
        };
        setQrPositions(updatedPositions);
        setDragStart({ x, y, pageIndex });
      }
    }
  };

  // 鼠标离开时，清除悬停
  const handleMouseLeave = () => {
    setHoverPos(null);
    setIsDragging(false);
  };

  // 处理Canvas点击事件
  const handleCanvasClick = (e, pageIndex) => {
    if (!qrText.trim()) {
      message.warning('请先输入二维码内容');
      return;
    }
    const canvas = e.target;
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    const scaleX = canvas.width / rect.width;
    const scaleY = canvas.height / rect.height;
    const pdfX = x * scaleX;
    const pdfY = canvas.height - (y * scaleY);
    const newPosition = {
      pageIndex,
      x: pdfX - qrSize / 2,
      y: pdfY - qrSize / 2,
      width: qrSize,
      height: qrSize
    };
    const existingIndex = qrPositions.findIndex(pos => pos.pageIndex === pageIndex);
    if (existingIndex >= 0) {
      const updatedPositions = [...qrPositions];
      updatedPositions[existingIndex] = newPosition;
      setQrPositions(updatedPositions);
    } else {
      setQrPositions([...qrPositions, newPosition]);
    }
    message.success(`第${pageIndex + 1}页二维码位置已设置`);
  };

  // 处理Canvas拖拽开始
  const handleMouseDown = (e, pageIndex) => {
    const canvas = e.target;
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    setIsDragging(true);
    setDragStart({ x, y, pageIndex });
  };

  // 处理Canvas拖拽结束
  const handleMouseUp = () => {
    setIsDragging(false);
  };

  // 生成PDF
  const handleGeneratePdf = async () => {
    if (!pdfFile) {
      message.error('请先选择PDF文件');
      return;
    }
    if (!qrText.trim()) {
      message.error('请输入二维码内容');
      return;
    }
    try {
      setLoading(true);
      const result = await window.api.addQRCodeToPdf({
        filePath: pdfFile,
        qrText: qrText.trim(),
        qrPositions: qrPositions
      });
      if (result.success) {
        const saveResult = await window.api.savePdfFile({
          pdfBytes: result.data,
          fileName: `output_${Date.now()}.pdf`
        });
        if (saveResult.success) {
          message.success('PDF生成成功！');
        } else {
          message.error('保存失败: ' + saveResult.error);
        }
      } else {
        message.error('生成失败: ' + result.error);
      }
    } catch (error) {
      message.error('生成PDF失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 预览PDF
  const handlePreview = () => {
    if (pdfPages.length === 0) {
      message.error('请先加载PDF文件');
      return;
    }
    setPreviewVisible(true);
  };

  // 清除所有二维码位置
  const handleClearPositions = () => {
    setQrPositions([]);
    message.success('已清除所有二维码位置');
  };

  useEffect(() => {
    console.log('useEffect触发:', { 
      pdfPagesLength: pdfPages.length, 
      currentPage, 
      hasCanvas: !!canvasRefs.current[currentPage] 
    });
    
    if (pdfPages.length > 0 && canvasRefs.current[currentPage]) {
      console.log('开始渲染页面:', currentPage);
      const { page, viewport } = pdfPages[currentPage];
      renderPage(page, viewport, canvasRefs.current[currentPage], currentPage);
    }
  }, [pdfPages, currentPage, qrPositions, hoverPos, qrSize]);

  return (
    <div style={{ padding: '20px' }}>
      <Title level={2}>PDF二维码编辑器</Title>
      
      <Row gutter={[16, 16]}>
        <Col span={8}>
          <Card title="文件操作" style={{ marginBottom: 16 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <Button 
                type="primary" 
                icon={<UploadOutlined />} 
                onClick={handleSelectPdf}
                loading={loading}
                block
              >
                选择PDF文件
              </Button>
              
              <Button 
                icon={<EyeOutlined />} 
                onClick={handlePreview}
                disabled={pdfPages.length === 0}
                block
              >
                预览PDF
              </Button>
            </Space>
          </Card>

          <Card title="二维码设置" style={{ marginBottom: 16 }}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Text>二维码内容：</Text>
                <TextArea
                  value={qrText}
                  onChange={(e) => setQrText(e.target.value)}
                  placeholder="请输入二维码内容"
                  rows={4}
                />
              </div>
              
              <div>
                <Text>二维码大小：{qrSize}px</Text>
                <Slider
                  min={60}
                  max={200}
                  value={qrSize}
                  onChange={setQrSize}
                  style={{ marginTop: 8 }}
                />
              </div>
              
              <Button 
                onClick={handleClearPositions}
                disabled={qrPositions.length === 0}
                block
              >
                清除所有位置
              </Button>
            </Space>
          </Card>

          <Card title="生成操作">
            <Button 
              type="primary" 
              icon={<DownloadOutlined />} 
              onClick={handleGeneratePdf}
              loading={loading}
              disabled={!pdfFile || !qrText.trim()}
              block
            >
              生成PDF
            </Button>
          </Card>
        </Col>

        <Col span={16}>
          <Card title={`PDF预览 (共${pdfPages.length}页)`}>
            {pdfPages.length > 0 ? (
              <div>
                <div style={{ marginBottom: 16 }}>
                  <Space>
                    <Button 
                      disabled={currentPage === 0}
                      onClick={() => setCurrentPage(currentPage - 1)}
                    >
                      上一页
                    </Button>
                    <Text>第 {currentPage + 1} 页</Text>
                    <Button 
                      disabled={currentPage === pdfPages.length - 1}
                      onClick={() => setCurrentPage(currentPage + 1)}
                    >
                      下一页
                    </Button>
                  </Space>
                </div>
                
                <div style={{ textAlign: 'center' }}>
                  <canvas
                    ref={(el) => {
                      if (el) canvasRefs.current[currentPage] = el;
                    }}
                    style={{ 
                      border: '1px solid #d9d9d9', 
                      cursor: 'crosshair',
                      maxWidth: '100%',
                      height: 'auto'
                    }}
                    onClick={(e) => handleCanvasClick(e, currentPage)}
                    onMouseDown={(e) => handleMouseDown(e, currentPage)}
                    onMouseMove={(e) => handleMouseMove(e, currentPage)}
                    onMouseUp={handleMouseUp}
                    onMouseLeave={handleMouseLeave}
                  />
                </div>
                
                <div style={{ marginTop: 16 }}>
                  <Text type="secondary">
                    点击画布设置二维码位置，拖拽可调整位置。最小尺寸60px。
                  </Text>
                </div>
              </div>
            ) : (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <Text type="secondary">请先选择PDF文件</Text>
              </div>
            )}
          </Card>
        </Col>
      </Row>

      {/* 预览模态框 */}
      <Modal
        title="PDF预览"
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        footer={null}
        width="80%"
        style={{ top: 20 }}
      >
        <div style={{ maxHeight: '70vh', overflow: 'auto' }}>
          {pdfPages.map((pageData, index) => (
            <div key={index} style={{ marginBottom: 20 }}>
              <Text strong>第 {index + 1} 页</Text>
              <canvas
                ref={(el) => {
                  if (el) {
                    const canvas = el;
                    const context = canvas.getContext('2d');
                    const viewport = pageData.viewport.clone({ scale: 0.5 });
                    canvas.width = viewport.width;
                    canvas.height = viewport.height;
                    
                    const renderContext = {
                      canvasContext: context,
                      viewport: viewport
                    };
                    
                    pageData.page.render(renderContext);
                  }
                }}
                style={{ 
                  border: '1px solid #d9d9d9',
                  maxWidth: '100%',
                  height: 'auto',
                  display: 'block',
                  margin: '10px auto'
                }}
              />
            </div>
          ))}
        </div>
      </Modal>
    </div>
  );
};

export default PdfQRCodeEditor; 